package com.example.demo.controller;

import com.example.demo.dto.AccessTokenDTO;
import com.example.demo.dto.GiteeUser;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import com.example.demo.provider.GiteeProvoder;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
//和第三方交接数据
@Controller
public class AuthorizeController {
    @Autowired
    private GiteeProvoder giteeProvoder;
    @Value("${gitee.client-id}")
    private String clientId;
    @Value("${gitee.client-uri}")
    private String clientUri;
    @Value("${gitee.client-secret}")
    private String clientSecret;
    @Autowired
    private UserService userService;
    @GetMapping("/callback")
    public String callback(@RequestParam(name="code")String code,
                           @RequestParam(name="state")String state,
                           HttpServletResponse response) throws IOException {
        AccessTokenDTO accessTokenDTO=new AccessTokenDTO();
        accessTokenDTO.setCode(code);
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setRedirect_uri(clientUri);
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setState(state);
        String accessToken= giteeProvoder.getAccessToken(accessTokenDTO);

        GiteeUser giteeUser =giteeProvoder.giteeUser(accessToken);
        if(giteeUser!=null && giteeUser.getId()!=null) {
            User user = new User();
            String token = UUID.randomUUID().toString();
            user.setAvatarUrl(giteeUser.getAvatar_url());
            user.setToken(token);
            user.setName(giteeUser.getName());
            user.setAccountId(toString().valueOf(giteeUser.getId()));
            user.setGmtCreate(System.currentTimeMillis());
            user.setGmtModified(user.getGmtCreate());
            userService.createOrUpdate(user);
            response.addCookie(new Cookie("token", token));
            return "redirect:/";
        }else {
            return "redirect:/";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response){
        request.getSession().removeAttribute("user");
        Cookie cookie=new Cookie("token",null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
